package com.pencilisland.pay.core.scheduler;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.pencilisland.pay.api.bean.constant.OrderConstant;
import com.pencilisland.pay.api.bean.mp.core.MessageRequest;
import com.pencilisland.pay.api.bean.mp.core.UpdateOrderREQ;
import com.pencilisland.pay.api.entity.TradeOrderEntity;
import com.pencilisland.pay.api.repository.TradeOrderRepository;
import com.pencilisland.pay.core.mp.service.impl.UpdateOrderMB;
import com.pencilisland.pay.core.service.RestService;

/**
 * 对于待支付的订单6分钟后自动撤销
 * 
 * @author Breeze
 *
 */
@Component
public class WxPayUnpayScheduler{

	Logger log = LoggerFactory.getLogger(getClass());
	
	@Autowired
	TradeOrderRepository tradeOrderRepo;
	
	@Autowired
	RestService restService;
	
	@Autowired
	UpdateOrderMB updateOrderMB;

	// 每分钟扫描清理未支付订单
	@Scheduled(cron = "0 0/1 * * * *")
	public void execute() throws Exception {

		log.info("【清理未支付订单开始】");

		List<TradeOrderEntity> tradeOrders = tradeOrderRepo.findByPayStatus(OrderConstant.PAY_STATUS_0);
		if (tradeOrders != null && !tradeOrders.isEmpty()) {
			List<UpdateOrderREQ.ElementOrders> updateOrders = new ArrayList<UpdateOrderREQ.ElementOrders>();
			for (TradeOrderEntity tradeOrder : tradeOrders) {
				LocalDateTime createTime = DateTimeFormatter.ofPattern("yyyyMMddHHmmss").parse(tradeOrder.getCreateTime(),LocalDateTime::from);
				LocalDateTime validateTime = createTime.plusMinutes(6);
				if(LocalDateTime.now().compareTo(validateTime)>=0){
					UpdateOrderREQ.ElementOrders updateOrder = new UpdateOrderREQ.ElementOrders();
					updateOrder.setOrderNo(tradeOrder.getOrderNo());
					updateOrder.setStatus(OrderConstant.STATUS_4);
					updateOrder.setFrom("APP");
					updateOrders.add(updateOrder);
				}
			}
			
			MessageRequest messageRequest = new MessageRequest();
			UpdateOrderREQ updateOrderReq = new UpdateOrderREQ();
			updateOrderReq.setOrders(updateOrders);
			messageRequest.setBody(updateOrderReq);
			updateOrderMB.process(messageRequest);
			
		}

	}

}
